package com.jiangxiaofei.citycloud.activity.fleamarket;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.blankj.utilcode.util.EmptyUtils;
import com.jiangxiaofei.citycloud.R;
import com.jiangxiaofei.citycloud.activity.user.LoginAcitivity;
import com.jiangxiaofei.citycloud.adapter.NeedListAdapter;
import com.jiangxiaofei.citycloud.adapter.FleaRecyTypeAdapter;
import com.jiangxiaofei.citycloud.base.BaseActivity;
import com.jiangxiaofei.citycloud.bean.BannerBean;
import com.jiangxiaofei.citycloud.bean.FleaMenuBean;
import com.jiangxiaofei.citycloud.bean.NeedBean;
import com.jiangxiaofei.citycloud.constants.BannerId;
import com.jiangxiaofei.citycloud.constants.Constants;
import com.jiangxiaofei.citycloud.constants.StringConstants;
import com.jiangxiaofei.citycloud.mvp.FleaConstant;
import com.jiangxiaofei.citycloud.mvp.FleaPersenter;
import com.jiangxiaofei.citycloud.mvp.MainConstant;
import com.jiangxiaofei.citycloud.mvp.MainPersenter;
import com.jiangxiaofei.citycloud.param.FleaNeedListParam;
import com.jiangxiaofei.citycloud.util.BannerViewHolder;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.zhouwei.mzbanner.MZBannerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * @author: JiangXFei
 * @date: 2017/11/8 0008
 * @content: 需求主页
 */

public class FleaMarketNeedActivity extends BaseActivity implements FleaConstant.GetFleaMenuView,
        FleaConstant.GetNeedListView, MainConstant.GetBannerView {
    public static final int MAINMENUID = 0;
    @InjectView(R.id.img_back)
    ImageView imgBack;
    @InjectView(R.id.tv_search_type)
    TextView tvSearchType;
    @InjectView(R.id.et_search)
    TextView etSearch;
    @InjectView(R.id.img_publish)
    TextView imgPublish;
    @InjectView(R.id.recy_flea_need)
    RecyclerView recyFleaNeed;
    @InjectView(R.id.banner)
    MZBannerView bannerView;
    @InjectView(R.id.rela_btn1)
    RelativeLayout relaBtn1;
    @InjectView(R.id.rela_btn2)
    RelativeLayout relaBtn2;
    @InjectView(R.id.rela_btn3)
    RelativeLayout relaBtn3;
    @InjectView(R.id.srf_layout)
    SmartRefreshLayout srfLayout;
    @InjectView(R.id.linear_search)
    LinearLayout linearSearch;

    private List<Integer> imgsList;
    private List<NeedBean> fleaNeedBeans = new ArrayList<>();
    private List<FleaMenuBean> fleaMenuType = new ArrayList<>();
    private NeedListAdapter needRecyAdapter;
    private PopupWindow mPopupWindowPublish;
    private View popupView;
    private RecyclerView recyType;
    private PopupWindow mTypePopupWindow;
    private View view;
    private FleaRecyTypeAdapter typeAdapter;
    private FleaConstant.GetFleanMenuPersenter getFleanMenuPersenter;
    private FleaNeedListParam needListParam;
    private FleaConstant.GetNeedListPersenter getNeedListPersenter;
    private int page = 1;
    private int typeId = 0;
    private BDLocation bdLocation;
    private String lat;
    private String lng;
    private int issue = 1;
    private MainConstant.GetBannerPersenter getBannerPersenter;


    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_flea_market_need_layout);
        mContext = this;
        mActivity = this;
        ButterKnife.inject(this);
        initAdapter();
        initPopupPublish();
        initRefres();
        initPopup();
        getFleanMenuPersenter = new FleaPersenter(mContext, (FleaConstant.GetFleaMenuView) mActivity);
        getFleanMenuPersenter.getMainFleaMenu();
        if (EmptyUtils.isNotEmpty(Constants.bdLocation)) {
            bdLocation = Constants.bdLocation;
        } else {
            Constants.bdclient.start();
            bdLocation = Constants.bdLocation;
        }
        lat = String.valueOf(bdLocation.getLatitude());
        lng = String.valueOf(bdLocation.getLongitude());
        needListParam = new FleaNeedListParam(page, typeId, lat, lng, issue);
        getNeedListPersenter = new FleaPersenter(mContext, (FleaConstant.GetNeedListView) mActivity);
        getNeedListPersenter.getNeedList();
        getBannerPersenter = new MainPersenter(mContext, (MainConstant.GetBannerView) mActivity);
        getBannerPersenter.getBanner();
    }

    /**
     * 初始化分类popupWindow
     */
    private void initPopup() {
        mTypePopupWindow = new PopupWindow(mContext);
        view = LayoutInflater.from(mContext).inflate(R.layout.popup_flea_type_item_layout, null);
        mTypePopupWindow.setContentView(view);
        mTypePopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mTypePopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mTypePopupWindow.setFocusable(true);
        mTypePopupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        recyType = view.findViewById(R.id.recy_type_item);
        typeAdapter = new FleaRecyTypeAdapter(R.layout.item_flea_popup_text_layout, fleaMenuType);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        recyType.setLayoutManager(linearLayoutManager);
        typeAdapter.setOnItemClickListener((adapter, view, position) -> {
            for (int i = 0; i < fleaMenuType.size(); i++) {
                fleaMenuType.get(i).setChecked(false);
            }
            fleaMenuType.get(position).setChecked(true);
            typeAdapter.notifyDataSetChanged();
            typeId = Integer.valueOf(fleaMenuType.get(position).getId());
            needListParam.setId(typeId);
            getNeedListPersenter.getNeedList();
            fleaNeedBeans.clear();
            needRecyAdapter.notifyDataSetChanged();
            mTypePopupWindow.dismiss();
        });
        recyType.setAdapter(typeAdapter);
    }

    /**
     * 初始化刷新框架
     */
    private void initRefres() {
        srfLayout.setRefreshHeader(new MaterialHeader(this).setShowBezierWave(true));
        srfLayout.setRefreshFooter(new BallPulseFooter(this).setSpinnerStyle(SpinnerStyle.Scale));
        srfLayout.setOnLoadmoreListener(refreshlayout -> {
            refreshlayout.finishLoadmore(2000);
            page++;
            needListParam.setPage(page);
            getNeedListPersenter.getNeedList();
        });
        srfLayout.setOnRefreshListener(refreshlayout -> {
            refreshlayout.finishRefresh(2000);
            page = 1;
            needListParam.setPage(page);
            fleaNeedBeans.clear();
            getNeedListPersenter.getNeedList();
        });
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        needRecyAdapter = new NeedListAdapter(R.layout.item_flea_need_layout, fleaNeedBeans);
        needRecyAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(mContext, FleaMarketNeedDetailActivity.class);
            intent.putExtra(StringConstants.FLEANEEDID, Integer.valueOf(fleaNeedBeans.get(position).getId()));
            startActivity(intent);
        });
        recyFleaNeed.setLayoutManager(linearLayoutManager);
        recyFleaNeed.setAdapter(needRecyAdapter);
    }


    @Override
    protected void setListener() {

    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {

    }


    @OnClick({R.id.img_back, R.id.img_publish, R.id.rela_btn1,
            R.id.rela_btn2, R.id.rela_btn3, R.id.linear_search})
    public void bOnClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                //返回
                finish();
                break;
            case R.id.img_publish:
                //发布
                if (EmptyUtils.isEmpty(Constants.userInfo)) {
                    Toast.makeText(mContext, "请先登陆！", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(this, LoginAcitivity.class));
                } else {
                    showPopup();
                }
                break;
            case R.id.rela_btn1:
                break;
            case R.id.rela_btn2:
                //分类
                mTypePopupWindow.showAsDropDown(relaBtn2);
                break;
            case R.id.rela_btn3:
                break;
            case R.id.linear_search:
                //搜索
                mActivity.startActivity(new Intent(mContext, FleaMarketSearchActivity.class));
                break;
            default:
                break;
        }
    }

    /**
     * 初始化发布popupWindow
     */
    private void initPopupPublish() {
        mPopupWindowPublish = new PopupWindow(mContext);
        popupView = LayoutInflater.from(mContext).inflate(R.layout.popup_ios_buttom, null);
        showAnimation(popupView);
        mPopupWindowPublish.setContentView(popupView);
        mPopupWindowPublish.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mPopupWindowPublish.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindowPublish.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPopupWindowPublish.setFocusable(true);
        mPopupWindowPublish.setOutsideTouchable(false);
        TextView tvGong = popupView.findViewById(R.id.tv_publish_gong);
        TextView tcXu = popupView.findViewById(R.id.tv_publish_xu);
        TextView tvCannel = popupView.findViewById(R.id.tv_cannel);
        tvGong.setOnClickListener(v -> {
            mPopupWindowPublish.dismiss();
            startActivity(new Intent(mContext, FleaMarketHavePublishActivity.class));
        });
        tvCannel.setOnClickListener(v -> mPopupWindowPublish.dismiss());
        tcXu.setOnClickListener(v -> {
            mPopupWindowPublish.dismiss();
            startActivity(new Intent(mContext, FleaMarketNeedPublishActivity.class));
        });
    }

    private void showPopup() {
        showAnimation(popupView);
        mPopupWindowPublish.showAtLocation(getCurrentFocus(), Gravity.BOTTOM, 0, 0); // 设置背景颜色变暗
        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
        lp.alpha = 0.7f;
        mActivity.getWindow().setAttributes(lp);
        mPopupWindowPublish.setOnDismissListener(() -> {
            WindowManager.LayoutParams lp1 = mActivity.getWindow().getAttributes();
            lp1.alpha = 1f;
            mActivity.getWindow().setAttributes(lp1);
        });
    }

    private void showAnimation(View popView) {
        AnimationSet animationSet = new AnimationSet(false);
        AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1.0f);
        alphaAnimation.setDuration(300);
        TranslateAnimation translateAnimation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0f
        );
        translateAnimation.setDuration(300);
        animationSet.addAnimation(alphaAnimation);
        animationSet.addAnimation(translateAnimation);
        popView.startAnimation(animationSet);
    }

    @Override
    public void setData(Object o) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void message(String str) {

    }

    @Override
    public int getFleaMenu() {
        return MAINMENUID;
    }

    @Override
    public void getFleaMainMenuOnSuccess(List<FleaMenuBean> fleaMenuBeans) {
        fleaMenuType.clear();
        if (fleaMenuBeans.size() > 0) {
            fleaMenuType.addAll(fleaMenuBeans);
        }
        typeAdapter.notifyDataSetChanged();
    }

    @Override
    public void getFleaSencendMenuOnSuccess(List<FleaMenuBean> fleaMenuBeans) {

    }

    @Override
    public void getFleaThreeMenuOnSuccess(List<FleaMenuBean> fleaMenuBeans) {

    }

    @Override
    public FleaNeedListParam getNeedListParam() {
        return needListParam;
    }

    @Override
    public void getNeedListOnSuccess(Object o) {
        List<NeedBean> beans = (List<NeedBean>) o;
        fleaNeedBeans.addAll(beans);
        needRecyAdapter.notifyDataSetChanged();
    }

    @Override
    public int getBannerParam() {
        return BannerId.FLEANEEDID;
    }

    @Override
    public void bannerSuccess(List<BannerBean> bannerBeans) {
        bannerView.setPages(bannerBeans, new BannerViewHolder(mContext));
        bannerView.start();
    }
}
